package com.zhijiaoyun.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alipay.api.domain.AlipayTradePayModel;
import com.zhijiaoyun.common.StringUtils;
import com.zhijiaoyun.dao.ICourseDao;
import com.zhijiaoyun.dao.IOrderDao;
import com.zhijiaoyun.dao.IOrderDetailDao;
import com.zhijiaoyun.dao.IShoppingCartDao;
import com.zhijiaoyun.model.Course;
import com.zhijiaoyun.model.Order;
import com.zhijiaoyun.model.OrderDetail;
import com.zhijiaoyun.model.ShoppingCart;
import com.zhijiaoyun.model.dto.OrderDetailDto;
import com.zhijiaoyun.model.dto.OrderDto;
import com.zhijiaoyun.model.dto.PageData;
import com.zhijiaoyun.model.dto.PageList;
import com.zhijiaoyun.service.IOrderDetailService;
import com.zhijiaoyun.service.IOrderService;

/**
 * @author shisfish
 * @date 2017/6/6
 */
@Service(value = "orderService")
public class OrderServiceImpl implements IOrderService {

	@Resource
	IOrderDao orderDao;
	
	@Resource
	IOrderDetailDao orderDetailDao;

	@Resource
	IShoppingCartDao shoppingCartDao;
	
	@Resource
	ICourseDao courseDao;

	@Resource
	IOrderDetailService orderDetailService;
	
	@Override
	public void addOrder(Order order) {
		orderDao.insert(order);
	}

	@Override
	public void addOrderByCartIds(String orderNum, String cartIds, long userId) {
		List<String> cartStrs = Arrays.asList(cartIds.split(","));
		try {
			List<ShoppingCart> shoppingCarts = shoppingCartDao.selectByCartIdsUserId(cartStrs, userId);
			if (!StringUtils.isEmptyList(shoppingCarts)) {
				BigDecimal price = new BigDecimal("0");
				String subject = "";
				for (ShoppingCart shoppingCart : shoppingCarts) {
					if (shoppingCart.getGoodsType() == 1) {
						Course course = courseDao.selectByPrimaryKey(shoppingCart.getGoodsId());
						price = price.add(course.getCurrentPrice());
						subject += course.getName() + ",";
					}
					OrderDetail detail = new OrderDetail(userId, orderNum, shoppingCart.getGoodsId(), shoppingCart.getGoodsType(), 1);
					orderDetailDao.insert(detail);
				}
				subject = subject.substring(0, subject.length() - 1);
				Order order = new Order(orderNum, userId, subject, subject, price, 1);
				orderDao.insert(order);
				
				// 刪除购物车
				shoppingCartDao.deleteByCartIds(cartStrs);
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Order getOrderByOrderNum(String orderNum) {
		return orderDao.selectByOrderNum(orderNum);
	}

	@Override
	public PageList<OrderDto> getOrderDtoByUserId(Integer pageIndex, int pageSize, long userId, int status) {
		int count = orderDao.countByParams(userId, status);
		PageData pageData = new PageData();
		List<OrderDto> listD = new ArrayList<>();
		PageList<OrderDto> pageList = new PageList<>();
		if (count > 0) {
			int pageIndexInt = pageIndex == null ? 1 : pageIndex;
			pageData = PageData.createPage(count, pageIndexInt, pageSize);
			List<Order> list = orderDao.pageByParams(pageData.getBeginIndex(), pageData.getPageSize(), userId, status);
			if (!StringUtils.isEmptyList(list)) {
				for (Order order : list) {
					List<OrderDetailDto> detailDtos = orderDetailService.getDtoByOrderNum(order.getOrderNum());
					if (!StringUtils.isEmptyList(detailDtos)) {
						OrderDto orderDto = new OrderDto(order, detailDtos);
						listD.add(orderDto);
					}
				}
			}
		}
		pageList = new PageList<>(listD, pageData);
		return pageList;
	}

	@Override
	public void modifyOrder(Order order) {
		orderDao.updateByPrimaryKey(order);
	}

	@Override
	public void addOrderByGoodsIdType(String orderNum, Long goodsId, Integer goodsType, Long userId) {
		if (goodsType == 1) {
			Course course = courseDao.selectByPrimaryKey(goodsId);
			if (course != null) {
				OrderDetail detail = new OrderDetail(userId, orderNum, goodsId, goodsType, 1);
				orderDetailDao.insert(detail);
				
				Order order = new Order(orderNum, userId, course.getName(), course.getName(), course.getCurrentPrice(), 1);
				orderDao.insert(order);
			}
		}
	}

	@Override
	public AlipayTradePayModel getAlipayTradePayModelByOrderNum(String orderNum) {
		Order order = orderDao.selectByOrderNum(orderNum);
		if (order != null) {
			AlipayTradePayModel model = new AlipayTradePayModel();
			model.setOutTradeNo(orderNum);
			List<OrderDetailDto> detailDtos = orderDetailService.getDtoByOrderNum(order.getOrderNum());
			if (!StringUtils.isEmptyList(detailDtos)) {
				StringBuffer subject = new StringBuffer();
				for (OrderDetailDto orderDetailDto : detailDtos) {
					subject.append(orderDetailDto.getCourseDto().getCourse().getName() + ",");
				}
				String descript = subject.substring(0, subject.length() - 1);
				model.setSubject(descript);
				model.setBody(descript);
				model.setTotalAmount(order.getPrice().toString());
			}
			model.setProductCode("FAST_INSTANT_TRADE_PAY");
			return model;
		}
		
		return null;
	}
	
	@Override
	public Order getOrderByGoodsId(Long goodsId, int goodsType, long userId) {
		return orderDao.selectOrderByGoodsId(goodsId, goodsType, userId);
	}

}
